﻿using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using System.Web;


namespace bmapi.Controllers
{
    public class CADQuery1Controller : CADController
    {
        /// <summary>
        /// 大前提  是当前登陆的流水线上的
        /// </summary>
        /// <param name="OrderName"></param>
        /// <param name="UserName"></param>
        /// <param name="lsh"></param>
        /// <returns></returns>
        [HttpGet, Route("cadQuery/queryinfo")]
        public string QueryOraderEtcInfo(string OrderName, string UserName, int lsh)
        {
            WriteLog("cadQuery/queryinfo", "OrderName:"+ OrderName+",UserName:"+UserName+",lsh:"+lsh, true);

            User user = GetUserByLoginID(GetCrrentIDByToken());
            if (user == null)
                return null;
            DataTable dt = null;
            if (string.IsNullOrEmpty(OrderName) && string.IsNullOrEmpty(UserName) && lsh == 0)
            {
                return null;
            }
            //三个条件都存在  优先根据订单名和流水号查询 订单名不存在 找流水号  流水号不存则返回空
            //以流水号为主(至于存在流水号的时候才有pod文件路径)  只有在单独填写订单名或者人名的情况下  订单名跟人名才起作用   订单名跟人名一起时  两个条件要同时满足
            else if (!string.IsNullOrEmpty(OrderName) && lsh != 0) //三个条件均不为空  订单名跟流水号不为0的情况
            {
                string sql = "select top 200 Order_tb.name as OrderName,Order_tb.state as State,order_id as OrderId,LSH_tb.Pod,LSH_tb.LSH,LSH_tb.name as UserName,Model_tb.name as ModelName from LSH_tb join Order_tb on order_id = id join Model_tb on Order_tb.o_model_id = Model_tb.id where Order_tb.name like '%" + OrderName + "%' and Order_tb.state != 0 and o_PLID = @plid";
                SQLCommand sc = new SQLCommand(sql, "@plid", user.PLID);
                dt = sc.ExecuteScalars();
                if (dt == null) //订单名没有
                    return SelectByLSHNoO(lsh, user.PLID);
                else
                    return SelectByLSHYO(dt, lsh);
            }
            else if ((!string.IsNullOrEmpty(UserName) && lsh != 0) || lsh != 0)//人名 lsh 不为0 跟 lsh 不为空的情况  判断流水号
            {                
                return SelectByLSHNoO(lsh, user.PLID); //无订单
            }
            else if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(OrderName)) //订单名跟人名 两条件同时满足
            {
                return SelectByUserNameAndOrderName(UserName, OrderName, user.PLID);
            }
            else if (!string.IsNullOrEmpty(UserName))//人名
            {
                return SelectByUserName(UserName, user.PLID);
            }
            else if (!string.IsNullOrEmpty(OrderName))
            {
                return SelectByOrderName(OrderName, user.PLID);
            }
            return "";
        }
        #region LSH 存在订单
        private string SelectByLSHYO(DataTable orderTable, int lsh)
        {
            string[] orderId = new string[orderTable.Rows.Count];
            int i = 0;
            foreach (DataRow item in orderTable.Rows)
            {
                orderId[i] = item["OrderId"].ToString();
                i++;
            }
            string orderids = AssistFun.ArryToString(orderId);
            string sql = "select top 200 Order_tb.name as OrderName,Order_tb.state as State,order_id as OrderId,LSH_tb.Pod,LSH_tb.LSH,LSH_tb.name as UserName,Model_tb.name as ModelName from LSH_tb join Order_tb on order_id = id join Model_tb on Order_tb.o_model_id = Model_tb.id where LSH_tb.LSH=@lsh and order_id in(" + orderids + ")";

            SQLCommand sc = new SQLCommand(sql, "@lsh", lsh);
            DataTable dt = sc.ExecuteScalars();
            if (dt == null)
                return ReturnQueryRes(null);
            else
                return ReturnResult(dt);

        }
        #endregion
        #region LSH 不存在订单 (人名跟lsh的搜索)
        private string SelectByLSHNoO(int lsh, int PLID)
        {
            string sql = "select top 200 Order_tb.name as OrderName,Order_tb.state as State,order_id as OrderId,LSH_tb.Pod,LSH_tb.LSH,LSH_tb.name as UserName,Model_tb.name as ModelName from LSH_tb join Order_tb on order_id = id join Model_tb on Order_tb.o_model_id = Model_tb.id where LSH_tb.LSH=@lsh and o_PLID=@plid and Order_tb.state!=0";
            SQLCommand sc = new SQLCommand(sql);
            sc.Add("@lsh", lsh);
            sc.Add("@plid", PLID);
            DataTable dt = sc.ExecuteScalars();
            if (dt == null)
                return ReturnQueryRes(null);
            else
                //return "订单不存在的流水号结果";
                return ReturnResult(dt);

        }
        #endregion
        #region 订单名
        private string SelectByOrderName(string OrderName, int PLID)
        {
            string sql = "select top 200 Order_tb.name as OrderName,Order_tb.state as State,order_id as OrderId,LSH_tb.Pod,LSH_tb.LSH,LSH_tb.name as UserName,Model_tb.name as ModelName from LSH_tb join Order_tb on order_id = id join Model_tb on Order_tb.o_model_id = Model_tb.id where Order_tb.name like '%" + OrderName + "%' and Order_tb.state!=0 and o_PLID=@plid";
            SQLCommand sc = new SQLCommand(sql, "@plid", PLID);
            DataTable dt = sc.ExecuteScalars();
            if (dt == null)
                return ReturnQueryRes(null);
            else
                //return 只有订单条件 且订单存在的结果";
                return ReturnResult(dt);

        }
        #endregion
        #region 人名
        private string SelectByUserName(string UserName, int PLID)
        {

            string sql = "select top 200 Order_tb.name as OrderName,Order_tb.state as State,order_id as OrderId,LSH_tb.Pod,LSH_tb.LSH,LSH_tb.name as UserName,Model_tb.name as ModelName from LSH_tb join Order_tb on order_id = id join Model_tb on Order_tb.o_model_id = Model_tb.id where LSH_tb.name=@uname and o_PLID=@plid and Order_tb.state!=0";

            SQLCommand sc = new SQLCommand(sql);
            sc.Add("@uname", UserName);
            sc.Add("@plid", PLID);
            DataTable dt = sc.ExecuteScalars();
            if (dt == null)
                return ReturnQueryRes(null);
            else
                //return 只有人名条件 且人名存在的结果";
                return ReturnResult(dt);

        }
        #endregion
        #region 人名跟订单名查询
        private string SelectByUserNameAndOrderName(string UserName, string OrderName, int PLID)
        {
            string sql = "select top 200 Order_tb.name as OrderName,Order_tb.state as State,order_id as OrderId,LSH_tb.Pod,LSH_tb.LSH,LSH_tb.name as UserName,Model_tb.name as ModelName from LSH_tb join Order_tb on order_id = id join Model_tb on Order_tb.o_model_id = Model_tb.id where Order_tb.name like'%" + OrderName + "%' and LSH_tb.name=@uname and o_PLID=@plid and Order_tb.state!=0";
            SQLCommand sc = new SQLCommand(sql);
            sc.Add("@uname", UserName);
            sc.Add("@plid", PLID);
            DataTable dt = sc.ExecuteScalars();
            if (dt == null)
                return ReturnQueryRes(null);
            else
                //return 只有人名跟订单名条件 且存在的结果";
                return ReturnResult(dt);

        }
        #endregion

        private string ReturnResult(DataTable dt)
        {
            List<OrderState> orderStates = AssistFun.DataTableToList<OrderState>(dt);
            List<PodPath> podPaths = GetPodPath(orderStates);
            if (podPaths.Count > 0)
                return ReturnQueryRes(podPaths);
            else
                return ReturnQueryRes(null);
        }

        /// <summary>
        /// 获取最终数据 
        /// </summary>
        /// <param name="orderStates"></param>
        /// <returns></returns>
        private List<PodPath> GetPodPath(List<OrderState> orderStates)
        {
            //对应的生产单已经完成  在历史目录中找pod文件
            string podPath = "";
            string path = "";
            string resPath = null;
            List<PodPath> podpaths = new List<PodPath>();
            foreach (OrderState item in orderStates)
            {
                path = GetOrderFile(item.OrderId, null);
                if (item.State == 2) //历史目录
                {
                    podPath = path + "\\pod\\" + item.OrderName + "[" + item.Pod + "]";
                    WriteDebug("GetPodPath", "OrderId:" + item.OrderId + ",State:" + item.State + ",podPath:" + podPath);
                    resPath = ReturnUrl(podPath);
                    
                }
                else if (item.State == 1)
                {
                    podPath = m_buyiRoot + "\\buyiWork\\" + item.OrderName + "\\pod\\" + item.OrderName + "[" + item.Pod + "]";
                    WriteDebug("GetPodPath", "OrderId:" + item.OrderId + ",State:" + item.State + ",podPath:" + podPath);
                    resPath = ReturnUrl(podPath);                    
                }
                if(resPath!=null)
                    podpaths.Add(new PodPath(item, ReturnUrl(podPath)));
            }
            return podpaths;
        }

        /// <summary>
        /// 判断pod是不是特体 
        /// </summary> 
        /// <param name="podPath"></param>
        /// <returns></returns>
        private string ReturnUrl(string podPath)
        {
            string path1 = (podPath + ".pod").ToLower();
            string path2 = (podPath + "#.pod").ToLower();
            if (File.Exists(path1))            
                return path1.Remove(0, path1.LastIndexOf("buyiroot")+9);
            else if (File.Exists(path2))
                return path2.Remove(0, path2.LastIndexOf("buyiroot")+9);
            else
                return null;
        }
        private string ReturnQueryRes(List<PodPath> podPaths)
        {
            XmlDocument doc = new XmlDocument();

            XmlNode root = doc.CreateElement("lsh");
            doc.AppendChild(root);

            XmlElement p = doc.CreateElement("status");
            p.InnerText = "200";
            root.AppendChild(p);

            XmlNode list = doc.CreateElement("lshList");
            root.AppendChild(list);

            if (podPaths == null)
            {
                p.InnerText = "201";
            }
            else
            {
                p.InnerText = "200";

                foreach (PodPath one in podPaths)
                {
                    XmlNode task = doc.CreateElement("lsh");
                    list.AppendChild(task);

                    p = doc.CreateElement("orderId");
                    p.InnerText = one.OrderId.ToString();
                    task.AppendChild(p);

                    p = doc.CreateElement("orderName");
                    p.InnerText = one.OrderName.ToString();
                    task.AppendChild(p);

                    p = doc.CreateElement("modelName");
                    p.InnerText = one.ModelName;
                    task.AppendChild(p);

                    p = doc.CreateElement("userName");
                    p.InnerText = one.UserName;
                    task.AppendChild(p);

                    p = doc.CreateElement("lshval");
                    p.InnerText = one.LSH.ToString();
                    task.AppendChild(p);

                    p = doc.CreateElement("pod");
                    p.InnerText = one.Pod.ToString();
                    task.AppendChild(p);

                    p = doc.CreateElement("podurl");
                    p.InnerText = one.PodUrl;
                    task.AppendChild(p);
                }
            }
            return ConvertXmlToString(doc);
        }
    }
    public class OrderState
    {
        public int OrderId { get; set; }
        public string OrderName { get; set; }
        public int State { get; set; }
        public int LSH { get; set; }
        public int Pod { get; set; }
        public string UserName { get; set; }
        //样板名 
        public string ModelName { get; set; }
    }
    public class PodPath : OrderState
    {
        public string PodUrl { get; set; }
        public PodPath() { }
        public PodPath(OrderState order, string podurl)
        {
            OrderId = order.OrderId;
            OrderName = order.OrderName;
            State = order.State;
            LSH = order.LSH;
            UserName = order.UserName;
            ModelName = order.ModelName;
            Pod = order.Pod;
            PodUrl = podurl;
        }
    }
}
